/**
 * Created by woody on 2017/2/28.
 */
import React from "react";
import {
    Alert,
    DeviceEventEmitter,
    ScrollView,
    Text,
    TextInput,
    TouchableHighlight,
    TouchableOpacity,
    View
} from "react-native";
import Util from "../../main/Util";
import Toast from "react-native-root-toast";
import {Actions} from "react-native-router-flux";
import * as MineAction from "../../redux/action/Mine";
import CustomStyle from "../../../common/style/CustomStyle";
import {connect} from "react-redux";
import {styles} from "./LoginUI";
import ModuleCommonHeader from "../../main/module/ModuleCommonHeader";

class Password extends React.Component {
    // 构造函数，可执行初始化操作
    constructor(props) {
        super(props);
        // 在ES6，在构造函数里初始化state
        this.state = {
            phone: this.props.phone,
            password: '',
            verifyCode: '',
            requestingVerifyCode: false,
            verifyText: '获取验证码',
            // verifyDisabled:false,
            // timeTick:0,
        };
        this._modifyPassword = this._modifyPassword.bind(this);
        this._requestVerifyCode = this._requestVerifyCode.bind(this);
    }

    // 组件被加载时
    componentDidMount() {
    }

    // 组件即将被卸载时
    componentWillUnmount() {
        this.interval && clearInterval(this.interval);
    }

    // 组件被渲染时
    render() {
        return (
            <ScrollView >
                <ModuleCommonHeader title={'修改密码'}/>
                <View

                    style={{
                        paddingLeft: CustomStyle.getActualSizeInHorizontal(20),
                        paddingRight: CustomStyle.getActualSizeInHorizontal(20),
                        marginTop: CustomStyle.getActualSizeInVertical(180),
                    }}
                >
                    <View style={[styles.inputContainer, {}]}>
                        <TextInput style={[CustomStyle.baseText, {flex: 1}]} placeholder={'请输入手机号'}
                                   keyboardType='numeric'
                                   maxLength={11}
                                   underlineColorAndroid={'#00000000'}
                                   onChangeText={(value) => {
                                       this.setState({phone: value});
                                   }}
                        />
                    </View>


                    <View style={[styles.inputContainer, {marginTop: CustomStyle.getActualSizeInVertical(40),}]}>
                        <TextInput style={[CustomStyle.baseText, {flex: 1}]} placeholder={'请输入密码'}
                                   underlineColorAndroid={'#00000000'}
                                   onChangeText={(value) => {
                                       this.setState({password: value});
                                   }}
                        />
                    </View>

                    <View style={{flexDirection: 'row', flex: 1, marginTop: CustomStyle.getActualSizeInVertical(80),}}>
                        <View style={[styles.inputContainer, {
                            flex: 1,
                        }]}>
                            <TextInput style={[CustomStyle.baseText, {flex: 1}]} placeholder={'请输入验证码'}
                                       underlineColorAndroid={'#00000000'}
                                       onChangeText={(value) => {
                                           this.setState({verifyCode: value});
                                       }}
                            />
                        </View>
                        <TouchableOpacity
                            disabled={this.state.requestingVerifyCode}
                            style={[, {
                                width: CustomStyle.getActualSizeInHorizontal(230),
                                height: CustomStyle.getActualSizeInVertical(88),
                                backgroundColor: this.state.requestingVerifyCode ? '#ebebeb' : '#ffc000',
                                justifyContent: 'center',
                                alignItems: 'center',
                                marginLeft: CustomStyle.getActualSizeInHorizontal(20),
                                borderRadius: CustomStyle.getActualSizeInHorizontal(4),
                            }
                            ]}
                            onPress={() => {
                                this._requestVerifyCode();
                            }}
                        >
                            <Text style={[CustomStyle.baseText, {
                                fontSize: CustomStyle.getActualFontSize(),
                                color: 'white',
                            }]}>{this.state.verifyText}</Text>
                        </TouchableOpacity>
                    </View>

                    <TouchableHighlight
                        style={[styles.btContainer, {
                            backgroundColor: '#ff7200',
                            marginTop: CustomStyle.getActualSizeInVertical(80),
                        }]}
                        underlayColor='#ef6500'
                        onPress={() => {
                            this._modifyPassword();
                        }}
                    >
                        <View >
                            <Text style={[CustomStyle.baseText, styles.btText,]}>确定</Text>
                        </View>
                    </TouchableHighlight>

                </View>
            </ScrollView>
        );
    }


    // 用户修改密码
    _modifyPassword() {
        if (this.state.phone && this.state.verifyCode && this.state.password) {
            const params = {
                phone: this.state.phone,
                code: this.state.verifyCode,
                password: this.state.password,
                userid: null
            };

            // this.props.rootview.setLoadingVisible(true, '正在注册中');
            Util.postServer("user/resetpass", params, (result) => this.onRegisterSuccess(result), (msg) => this.onLoginFailed(msg));
        } else {
            Alert.alert("错误", "请输入完整信息");
        }
    }

    // 注册成功回调
    onRegisterSuccess(result) {
        if (result.status === '0') {
            const user = Util.getUser();
            if (user.token) {
                Util.storage.clearMapForKey('users');
                this.props.updateUser({});
                DeviceEventEmitter.emit('password', ' ');
                Toast.show("修改成功,请重新登录", {duration: Toast.durations.SHORT, position: Toast.positions.CENTER});
            } else {
                Toast.show("修改成功", {duration: Toast.durations.SHORT, position: Toast.positions.CENTER});
            }
            Actions.pop({key: 'Mine'});
        }
        else {
            Alert.alert("修改失败", result.msg);
        }

    }

    // 注册失败回调
    onLoginFailed(msg) {
        // this.props.rootview.setLoadingVisible(false, '');
        Toast.show(msg, {duration: Toast.durations.SHORT, position: Toast.positions.CENTER});
    }

    _requestVerifyCode() {
        if (!this.state.phone || this.state.phone.length < 11) {
            Alert.alert('错误', '请输入正确的手机号');
            return;
        }

        if (this.state.requestingVerifyCode)
            return;

        this.state.requestingVerifyCode = true;
        this.interval && clearInterval(this.interval);
        this.cd = 60;
        this.interval = setInterval(
            () => {
                this.cd--;
                this.setState({
                    verifyText: this.cd === 0 ? '获取验证码' : this.cd + '秒',
                    requestingVerifyCode: this.cd !== 0
                });
                if (this.cd === 0) {
                    this.interval && clearInterval(this.interval);
                    this.interval = null;
                }
            }, 1000
        )

        const params = {
            phone: this.state.phone,
        };
        Util.postServer('user/code', params, (result) => this.onGetVerifyCodeSuccess(result), (msg) => this.onGetVerifyCodeFailed(msg));
    }


    // tickTime(param)
    // {
    //     // var tick = timeTick + 1;
    //     // this.setState({ timeTick:tick });
    //     Alert.alert( "Title", param );
    // }


    onGetVerifyCodeSuccess(result) {
        if (result.status !== '0') {
            Toast.show(result.msg, {duration: Toast.durations.SHORT, position: Toast.positions.CENTER});
        }
        else {
            Toast.show("短信验证码已发送", {duration: Toast.durations.SHORT, position: Toast.positions.CENTER});
        }
    }

    onGetVerifyCodeFailed(msg) {
        Toast.show(msg, {duration: Toast.durations.SHORT, position: Toast.positions.CENTER});
    }
}

const mapStateToProps = (state) => {
    return {};
};

const mapDispatchToProps = (dispatch) => {
    return {
        updateUser: param => dispatch(MineAction.userData(param)),
    };
};

export default connect(mapStateToProps, mapDispatchToProps)(Password);
